import React, { useState } from 'react'
import style from './index.module.scss'
import { Avatar, Radio, Dropdown, Space, Modal, Form, Input, Upload } from 'antd'
import { WomanOutlined, ManOutlined, UserOutlined, BarsOutlined, PlusOutlined } from '@ant-design/icons'
import Bottom from './Bottom'
import { message } from 'antd'
import { findInfo, updateUser } from '@/common/api'
import { useEffect } from 'react'
import { getLs, setLs } from '@/common/common'
import { connect } from 'react-redux'
import { asyncAddUser, asyncGetPrivacy } from '@/store/actions'
import Fans from './Fans/Fans'
import _ from 'lodash'
import PrivacyList from './PrivacyList'


function Info(props) {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm(); // 创建表单实例 
  const [privacyForm] = Form.useForm();
  const [avator, setAavator] = useState({})
  const [fansShow, setFansShow] = useState(false)
  const [type, setType] = useState('fansShow')
  const [privacy, setPrivacy] = useState(false)
  const [userInfo,setUserInfo] = useState({})
  const items = [
    {
      label: <span onClick={() => setIsModalOpen(true)}>修改资料</span>,
      key: '0',
    },
    {
      label: <span onClick={() => setPrivacy(true)}>隐私设置</span>,
      key: '1',
    },
  ];
  useEffect(() => {
    getUserInfoApi()
    
  }, [])
  // 获取用户信息
  const getUserInfoApi = async()=>{
    const { username,_id } = getLs('userInfo')
    props.addPrivacy({userId:_id})
    const RES = await findInfo({username})
    setUserInfo(RES.data)
  }
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const handleOk = async () => {
    try {
       await form.validateFields()
      const params = form.getFieldValue()
      const newParams = {
        ...params,
        username: userInfo.username,
        avator
      }
      const RES = await updateUser(newParams)
      if(RES.code===200){
        setLs(RES.data, 'userInfo')
        getUserInfoApi()
        message.success("修改成功")
      }
    } catch (err) {
      return false
    }
    // 在这里处理表单数据，例如发送到API  
    setIsModalOpen(false); // 关闭Modal  
  };
  // 图片校验
  const [fileList, setFileList] = useState([]);
  const handleChange = ({ fileList: newFileList, file }) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      return false
    }
    if (newFileList.length === 0) {
      setAavator({})
      setFileList(newFileList);
      return
    }
    setAavator(file)
    setFileList(newFileList);
  }
  const uploadButton = (
    <button
      style={{
        border: 0,
        background: 'none',
      }}
      type="button"
    >
      <PlusOutlined />
      <div
        style={{
          marginTop: 8,
        }}
      >
        点击上传
      </div>
    </button>
  );
  const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('你只能上传JPG/PNG 的文件!');
      return false
    }
    return false
  };

  // 校验用户名
  const valiDatateName = (_, value) => {
    if (!value) {
      return Promise.reject(new Error('请输入用户名！'));
    }
    return Promise.resolve();
  }
  // 关注与粉丝的modal
  const updateFans = (value)=>{
    setFansShow(value)
  }
  const peopleShow = async(value)=>{
    updateFans(true);
    setType(value)
  }
  return (
    <div className={style.Info}>
      <div className={style.header}>
        <div className={style.left}>
          {!userInfo?.avator?<Avatar src={`localhost:5000//${userInfo?.avator}`} icon={<UserOutlined />} size={180} />
          :<Avatar src={`http://localhost:5000${userInfo?.avator}`} size={180} />}
        </div>
        <div className={style.right}>
          <div className={style.title}>
            <h1>{userInfo?.name || '趣纷享'}</h1>
            <Dropdown menu={{ items }} trigger={['click']}>
              <Space>
                <BarsOutlined />
              </Space>
            </Dropdown>
          </div>
          <p>纷享号:{userInfo?.username} | 地址: 四川</p>
          <div>{userInfo?.signature || '还没有简介...'}</div>
          <div className={style.sex}>
            {userInfo?.sex==0?<WomanOutlined style={{ color: "#fe8495" }} />:
            <ManOutlined style={{ color: "blue" }}/>}
          </div>
          <div className={style.attention}>
            <span onClick={() => peopleShow('attentionShow')}><i style={{ marginRight: "5px" }}>{_.get(userInfo,'attentionNumber')||0}</i>关注</span>
            <span onClick={()=>peopleShow('fansShow')}><i style={{ marginRight: "5px" }}>{_.get(userInfo,'fansNumber')||0}</i>粉丝</span>
          </div>
        </div>
      </div>
      <Modal className={style.modal} title="修改资料" okText="修改" cancelText="取消" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <Form
          form={form}
        >
          <Form.Item label="名字" initialValue={userInfo.name} rules={[{ validator: valiDatateName }]} name="name">
            <Input/>
          </Form.Item>
          <Form.Item label="纷享号" name="username">
            <Input placeholder={userInfo?.username} disabled />
          </Form.Item>
          <Form.Item initialValue={userInfo.sex} label="性别" rules={[{ required: true, message: "请选择性别" }]} name="sex">
            <Radio.Group>
              <Radio value={1}>我是男生</Radio>
              <Radio value={0}>我是女生</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item initialValue={userInfo.signature} label="个人简介" name="signature">
            <Input showCount maxLength={20} />
          </Form.Item>
          <Form.Item label="上传头像" name="avator">
            <Upload
              listType="picture-card"
              fileList={fileList}
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              {fileList.length < 1 && uploadButton}
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        open={privacy}
        onCancel={() => setPrivacy(false)}
        title="隐私设置"
        footer={null}
      >
        <PrivacyList userId={ userInfo._id} />
      </Modal>
      <Fans isUser Id={userInfo._id} setUserInfo={setUserInfo} fansShow={fansShow} type={type} updateFansShow={()=>updateFans(false)}/>
      <Bottom />
      
    </div>
  )
}
export default connect((state => {
  return {
    userInfo: state.user.userInfo,
    privacy:state.privacy.privacyList
  }
}), dispatch => {
  return {
    addUser: (val) => asyncAddUser(dispatch, val),
    updateUser: (val) => dispatch({ type: "addUser", payload: val }),
    addPrivacy:(val)=>asyncGetPrivacy(dispatch,val)
  }
})(Info)